package cn.yunyichina.provider.pay.icbc.utils;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

import org.jdom.Document;
import org.jdom.output.XMLOutputter;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;


public class Tools {

	/**
	 * 获取当前日期，格式：4 位年＋2位月＋2位日
	 * @return yyyymmdd
	 */
	public static String getDate() 
	{
		String strDate = null;

		Calendar rightNow = Calendar.getInstance();
		int year = rightNow.get(Calendar.YEAR);
		String strYear = String.valueOf(year);
		strYear = fillChar(strYear, '0', 4, true);
		int month = rightNow.get(Calendar.MONTH) + 1;
		String strMonth = String.valueOf(month);
		strMonth = fillChar(strMonth, '0', 2, true);
		int day = rightNow.get(Calendar.DAY_OF_MONTH);
		String strDay = String.valueOf(day);
		strDay = fillChar(strDay, '0', 2, true);

		strDate = strYear + strMonth + strDay;

		return strDate;
	}

	/**
	 * 获取当前时间，格式：2位时＋2位分
	 * @return HHMM
	 */
	public static String getTime()
	{
		String strTime = null;

		Calendar rightNow = Calendar.getInstance();

		int hour = rightNow.get(Calendar.HOUR_OF_DAY);
		String strHour = String.valueOf(hour);
		strHour = fillChar(strHour, '0', 2, true);

		int minute = rightNow.get(Calendar.MINUTE);
		String strMinute = String.valueOf(minute);
		strMinute = fillChar(strMinute, '0', 2, true);

		/*
		int second=rightNow.get(Calendar.SECOND);
		String strSecond=String.valueOf(second);		
		strSecond=fillChar(strSecond,'0',2,true);			
		*/
		//strTime=strHour+strMinute+strSecond;		
		strTime = strHour + strMinute;
		return strTime;

	}

	/**
	 * 获取当前时间，格式：2位时＋2位分＋2位秒
	 * @return HHMMSS
	 */
	public static String getTimeSec()
	{
		String strTime = null;

		Calendar rightNow = Calendar.getInstance();

		int hour = rightNow.get(Calendar.HOUR_OF_DAY);
		String strHour = String.valueOf(hour);
		strHour = fillChar(strHour, '0', 2, true);

		int minute = rightNow.get(Calendar.MINUTE);
		String strMinute = String.valueOf(minute);
		strMinute = fillChar(strMinute, '0', 2, true);

		int second = rightNow.get(Calendar.SECOND);
		String strSecond = String.valueOf(second);
		strSecond = fillChar(strSecond, '0', 2, true);

		strTime = strHour + strMinute + strSecond;
		//strTime = strHour + strMinute;
		return strTime;

	}
	
	/**
	 * 获取当前时间，格式：2位时＋2位分＋2位秒+3毫秒+000
	 * @return HHMMSSNNN000
	 */
	public static String getTimeMillisec()
	{
		String strTime = null;

		Calendar rightNow = Calendar.getInstance();

		int hour = rightNow.get(Calendar.HOUR_OF_DAY);
		String strHour = String.valueOf(hour);
		strHour = fillChar(strHour, '0', 2, true);

		int minute = rightNow.get(Calendar.MINUTE);
		String strMinute = String.valueOf(minute);
		strMinute = fillChar(strMinute, '0', 2, true);

		int second = rightNow.get(Calendar.SECOND);
		String strSecond = String.valueOf(second);
		strSecond = fillChar(strSecond, '0', 2, true);

		int msecond = rightNow.get(Calendar.MILLISECOND);
		String mstrSecond = String.valueOf(msecond);
		mstrSecond = fillChar(mstrSecond, '0', 3, true);

		strTime = strHour + strMinute + strSecond +mstrSecond+"000";
		//strTime = strHour + strMinute;
		return strTime;

	}

	
	/**
	 * 获取当前日期时间，格式：4位年＋2位月＋2位日+2位时＋2位分
	 * @return YYYYMMDDHHMM
	 */
	public static String getDateTime() {
		return getDate() + getTime();
	}

	/**
	 * 获取当前日期时间，格式：4位年＋2位月＋2位日+2位时＋2位分＋2位秒
	 * @return YYYYMMDDHHMMSS
	 */
	public static String getDateTime2() {
		return getDate() + getTimeSec();
	}

	/**
	 * 填充函数，可左/右补字符
	 * @param sSource 需填充的源String
	 * @param ch 填充的字符
	 * @param nLen 填充后长度
	 * @param bLeft 左填充为true，右填充为false
	 * @return 填充后String
	 */
	public static String fillChar(
		String sSource,
		char ch,
		int nLen,
		boolean bLeft) {
		int nSrcLen = sSource.getBytes().length;

		if (nSrcLen <= nLen) { //左填充
			if (bLeft)
				for (int i = 0; i < (nLen - nSrcLen); i++)
					sSource = ch + sSource;
			else //右填充
				for (int i = 0; i < (nLen - nSrcLen); i++)
					sSource += ch;
		}

		return (sSource);
	}

	/**
	 * 文件复制
	 * @param source 源文件
	 * @param dest 目标文件
	 */
	public static void fileCopy(
		String source,
		String dest) //文件拷贝                                                                                                                                                                                                                                                                                                                                                                     
	{
		try {
			File destFile = new File(dest);
			if (destFile.exists()) {
				for (int i = 0; i < 3; i++) {
					if (!destFile.delete()) {
						System.out.println(
							"[" + Tools.getDateTime2() + "]删除原文件失败！");
						i += 1;
					} else {
						System.out.println(
							"[" + Tools.getDateTime2() + "]删除原文件成功！");
						break;
					}
				}
			}
			File srcFile = new File(source);
			long fileLen = srcFile.length();
			destFile = null;
			InputStream is = new FileInputStream(srcFile);
			PrintWriter writer =
				new PrintWriter(new BufferedWriter(new FileWriter(dest)));

			byte[] buf = new byte[(int) fileLen];

			is.read(buf, 0, (int) fileLen);
			String str = new String(buf);

			writer.println(str.trim());
			is.close();
			writer.close();

		} catch (IOException e) {
			//			mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, e);
			//			mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,
			//					"复制发送文件失败！！");
			e.printStackTrace();
		}

	}

	/**
	 * 读文件到String
	 * @param source 源文件
	 * @return 文件内容String
	 */
	public static String fileToStr(String source) {
		String dest = "";
		try {
			File sourceFile = new File(source);
			InputStream is = new FileInputStream(sourceFile);
			long fileLen = sourceFile.length();
			byte[] rbytes = new byte[(int) fileLen];
			is.read(rbytes, 0, (int) fileLen);
			dest = new String(rbytes, 0, (int) fileLen);
		} catch (IOException ioe) {
			ioe.printStackTrace();
//			mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, "文件转换为字符串时失败！！");
		}
		return dest;

	}
	
	/**
	 * 写入String到指定文件中
	 * @param source
	 * @param destFile
	 */
	public static void str2File(String source, String destFile) {
		try {
			File dest = new File(destFile);
			if (dest.exists()) {
				dest.delete();
			}
			OutputStream os = new FileOutputStream(dest);
			os.write(source.getBytes());
			os.close();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
	
	/**
	 * 检查输入的字符是否有xml的转义字符，如果有，则改成原字符
	 * @param s
	 * @return
	 */
	public static String xmlFormat(String s) {
		int idx = 0;
		int sLength = s.length();
		int offset = 0;
		String subS = null;
		String newS = "";
		do {
			idx = s.indexOf("&lt;", offset);
			if (idx == -1) {
				newS = s;
				break;
			}
			subS = s.substring(offset, idx);
			newS = newS + subS + "<";
			offset = idx + 1;
			System.out.println("＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝执行了一次左中括号转义＝＝＝＝＝＝＝＝＝＝＝");
		} while (idx != -1);
		s = newS;
		idx = 0;
		sLength = s.length();
		offset = 0;
		subS = null;
		newS = "";
		do {
			idx = s.indexOf("&gt;", offset);
			if (idx == -1) {
				newS = s;
				break;
			}
			subS = s.substring(offset, idx);
			newS = newS + subS + ">";
			offset = idx + 1;
			System.out.println("＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝执行了一次右中括号转义＝＝＝＝＝＝＝＝＝＝＝");
		} while (idx != -1);
		s = newS;
		idx = 0;
		sLength = s.length();
		offset = 0;
		subS = null;
		newS = "";
		do {
			idx = s.indexOf("&amp;", offset);
			if (idx == -1) {
				newS = s;
				break;
			}
			subS = s.substring(offset, idx);
			newS = newS + subS + "&";
			offset = idx + 1;
			System.out.println("＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝执行了一次\"&\"号转义＝＝＝＝＝＝＝＝＝＝＝");
		} while (idx != -1);
		return newS;
	}
	
	/**
	 * 检查输入的字符是否有xml不可识别的字符，如果有，则改成转义字符
	 * @param s xml数据源
	 * @return 转义后xml
	 */
	public static String xmlFormat2(String s) {
		int idx = 0;
		int sLength = s.length();
		int offset = 0;
		String subS = null;
		String newS = "";
		do {
			idx = s.indexOf("<", offset);
			if (idx == -1) {
				newS = s;
				break;
			}
			subS = s.substring(offset, idx);
			newS = newS + subS + "&lt;";
			offset = idx + 1;
			System.out.println("＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝执行了一次左中括号转义＝＝＝＝＝＝＝＝＝＝＝");
		} while (idx != -1);
		s = newS;
		idx = 0;
		sLength = s.length();
		offset = 0;
		subS = null;
		newS = "";
		do {
			idx = s.indexOf(">", offset);
			if (idx == -1) {
				newS = s;
				break;
			}
			subS = s.substring(offset, idx);
			newS = newS + subS + "&gt;";
			offset = idx + 1;
			System.out.println("＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝执行了一次右中括号转义＝＝＝＝＝＝＝＝＝＝＝");
		} while (idx != -1);
		s = newS;
		idx = 0;
		sLength = s.length();
		offset = 0;
		subS = null;
		newS = "";
		do {
			idx = s.indexOf("&", offset);
			if (idx == -1) {
				newS = s;
				break;
			}
			subS = s.substring(offset, idx);
			newS = newS + subS + "&amp;";
			offset = idx + 1;
			System.out.println("＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝执行了一次\"&\"号转义＝＝＝＝＝＝＝＝＝＝＝");
		} while (idx != -1);
		return newS;
	}
	
	/**
	 * 取得Visa报文所需格式的日期
	 * @return
	 */
	public static String getVisaTime() {
		Calendar rightNow = Calendar.getInstance(); //日历的基类
		int year = rightNow.get(Calendar.YEAR);
		int month = rightNow.get(Calendar.MONTH) + 1;
		int day = rightNow.get(Calendar.DAY_OF_MONTH);
		int hour = rightNow.get(Calendar.HOUR_OF_DAY);
		int minute = rightNow.get(Calendar.MINUTE);
		int second = rightNow.get(Calendar.SECOND);
		String visaTime = Integer.toString(year) + Integer.toString(month)
				+ Integer.toString(day) + " " + Integer.toString(hour) + ":"
				+ Integer.toString(minute) + ":" + Integer.toString(second);
		return visaTime;
	}
	
	/**
	 * 将jdom的Document对象转换为相应的String
	 * @param doc
	 * @param encoding
	 * @return
	 */
	public static String doc2String(Document doc, String encoding) {
//		String repString = null;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			XMLOutputter outputter = new XMLOutputter("\t", false, encoding);
			outputter.output(doc, baos);
		} catch (java.io.IOException e) {
			e.printStackTrace();
			return null;
		}
		return baos.toString();
	}
	
	public static byte[] getFromBASE64(String s) {
		if (s == null)
			return null;
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			return decoder.decodeBuffer(s);
		} catch (Exception e) {
			return null;
		}
	}
	
	public static String getrevFromBASE64(String s) {
		if (s == null)
			return null;
		BASE64Encoder encoder = new BASE64Encoder();
		try {
			return encoder.encode(s.getBytes());
		} catch (Exception e) {
			return null;
		}
	}
	
}
